package com.dongdongshop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.IdWorker;
import com.dongdongshop.vo.CartVO;
import com.dongdongshop.vo.OrderVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@DubboService
public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public OrderVO toAddOrder(TbOrder order) {
        List<CartVO> cartList = (List<CartVO>) redisTemplate.opsForHash().get("cartVOList",order.getUserId());

        String WIDtotal_amount = null;//付款金额

        for (CartVO cart : cartList) {
            IdWorker IdWorker = new IdWorker();
            long orderId = IdWorker.nextId();
            TbOrder tbOrder = new TbOrder();//新建订单对象
            tbOrder.setOrderId(orderId);//订单id
            tbOrder.setUserId(order.getUserId());//用户名
            tbOrder.setPaymentType(order.getPaymentType());//支付类型
            tbOrder.setStatus("1");//状态：未支付
            tbOrder.setCreateTime(new Date());//订单创建时间
            tbOrder.setUpdateTime(new Date());//订单更新时间
            tbOrder.setReceiverAreaName(order.getReceiverAreaName());//地址
            tbOrder.setReceiverMobile(order.getReceiverMobile());//手机号
            tbOrder.setReceiver(order.getReceiver());//收货人
            tbOrder.setSourceType("2");//订单来源
            tbOrder.setSellerId(cart.getSellerId());//商家id
            tbOrder.setOutTradeNo(order.getOutTradeNo());
            //循环购物车明细
            double money = 0;
            for (TbOrderItem orderItem : cart.getOrderItemsList()) {
                orderItem.setId(IdWorker.nextId());
                orderItem.setOrderId(orderId);//订单id
                orderItem.setSellerId(cart.getSellerId());
                money += orderItem.getTotalFee().doubleValue();//金额累加
                orderItem.setOutTradeNo(order.getOutTradeNo());
                tbOrderItemMapper.insertSelective(orderItem);
            }
            tbOrder.setPayment(new BigDecimal(money));
            WIDtotal_amount = tbOrder.getPayment() + "";
            tbOrderMapper.insertSelective(tbOrder);
        }
        redisTemplate.opsForHash().delete("cartVOList",order.getUserId());
        OrderVO orderVO = new OrderVO();
        orderVO.setWidout_trade_no(order.getOutTradeNo());//商户订单号
        orderVO.setWidtotal_amount(WIDtotal_amount);//付款总金额
        orderVO.setWidsubject("购物车付款");//订单名称，必填
        orderVO.setWidbody("东东商品");//商品描述，可空
        return orderVO;
    }

    @Override
    @Transactional
    public void updateOutTradeNo(String out_trade_no, String trade_no) {
        tbOrderMapper.updateByTradeNo(out_trade_no,trade_no);
        tbOrderItemMapper.updateByTradeNo(out_trade_no,trade_no);
    }

    @Override
    public List<CartVO> selectInfo(String username, String outTradeNo, String tradeNo) {
        List<CartVO> cartVOList =(List<CartVO>) redisTemplate.boundHashOps("itemList").get(username);

        for (CartVO cartVO : cartVOList) {
            cartVO.setOutTradeNo(outTradeNo);
            cartVO.setTradeNo(tradeNo);
        }
        if(cartVOList == null){
            cartVOList = new ArrayList<>();//防止空指针
        }
        return cartVOList;
    }

    @Override
    public void updateScore(String out_trade_no) {
        List<TbOrder> list = tbOrderMapper.selectByScore(out_trade_no);
        double payment = 0;
        String userId = list.get(0).getReceiver();;
        for (int i = 0; i < list.size(); i++) {
            payment += list.get(i).getPayment().doubleValue();
        }
        //先发送半消息
        Map map = new HashMap();
        map.put("userId",userId);
        map.put("totalScore",payment);
        map.put("expendScore",0);
        map.put("created",new Date());
        map.put("updated",new Date());
        //要发送的消息
        Message<String> message = MessageBuilder.withPayload(JSONObject.toJSONString(map)).build();
        //发送事物消息 1.表示事物消息发送者的组 2.表示topic 3.要发送的消息内容 4.我们执行本地事物需要用到的参数
        rocketMQTemplate.sendMessageInTransaction("dk2107-tx-group","order-score-topic",message,userId);
        System.out.println(message);

    }
}
